<template>
  <BasicModal :title="title" :width="800" v-bind="$attrs" @register="registerModal">
    <BasicForm @register="registerForm" />
    <template #footer>
      <Button @click="closeModal">取消</Button>
      <Button @click="handleSave" type="primary" class="button-color-green">保存</Button>
      <Button type="primary" @click="handleOk">生成代码</Button>
    </template>
  </BasicModal>
  <PreviewCodeModel @register="previewCodeModel" />
</template>

<script lang="ts" setup>
  import { computed, ref, unref } from "vue"
  import { Button } from "ant-design-vue"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { BasicModal, useModalInner } from "/@/components/Modal"
  import PreviewCodeModel from "./PreviewCodeModel.vue"
  import { useModal } from "/@/components/Modal"
  import { genCode, updateGenTable, getGenInfo } from "../codeGen.api"
  import { genCodeFormSchema } from "../codeGen.data"
  import { listTemplateGroup } from "../../templateGroup/templateGroup.api"
  import { useMessage } from "/@/hooks/web/useMessage"
  const { createMessage } = useMessage()
  const emit = defineEmits(["success", "register"])
  const props = defineProps({
    rootTreeData: { type: Array, default: () => [] },
  })
  const isUpdate = ref<boolean>(false)
  // 当前的弹窗数据
  // const model = ref<object>({})
  const title = computed(() => "生成代码")
  const genInfo = ref<any>({})

  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    schemas: genCodeFormSchema,
    labelWidth: "100px",
    showActionButtonGroup: false,
    wrapperCol: { lg: 24, md: 24 },
  })

  const [previewCodeModel, { openModal: openPreviewCodeModel }] = useModal()

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields()
    setModalProps({ loading: true, confirmLoading: false })
    try {
      const { id } = unref(data)
      // 获取所有模板组
      const templateGroupList = await listTemplateGroup({})
      // 获取生成信息
      genInfo.value = await getGenInfo(id)
      updateSchema([
        {
          field: "templateGroupId",
          componentProps: ({ formModel, formActionType }) => {
            return {
              optionFilterProp: "label",
              showSearch: true,
              options: templateGroupList,
              onChange: async (templateGroupId: any) => {
                if (!templateGroupId) {
                  return
                }
              },
            }
          },
        },
        {
          field: "packageName",
          componentProps: ({ formModel, formActionType }) => {
            return {
              optionFilterProp: "label",
              allowClear: true,
              options: genInfo.value.packageNameList,
            }
          },
        },
        {
          field: "author",
          componentProps: ({ formModel, formActionType }) => {
            return {
              optionFilterProp: "label",
              allowClear: true,
              options: genInfo.value.authorList,
            }
          },
        },
      ])

      const defaultTemplateGroupId = templateGroupList.length > 0 ? templateGroupList[0].value : undefined
      // 赋默认值
      await setFieldsValue({
        genTableId: id,
        ...genInfo.value,
        templateGroupId: defaultTemplateGroupId || genInfo.value.templateGroupId,
      })
    } finally {
      setModalProps({ loading: false })
    }
  })

  const handleSave = async () => {
    setModalProps({ confirmLoading: true })
    try {
      let values = await validate()
      await updateGenTable(values)
      closeModal()
      createMessage.success("保存成功")
      emit("success")
    } finally {
      setModalProps({ confirmLoading: false })
    }
  }

  async function handleOk() {
    try {
      setModalProps({ confirmLoading: true })
      let values = await validate()
      console.log("gen code from: ", values)
      const codeList = await genCode(values)
      openPreviewCodeModel(true, { list: codeList })
      // await saveOrUpdateDepart(values, isUpdate.value)
      closeModal()
      emit("success")
    } finally {
      setModalProps({ confirmLoading: false })
    }
  }
</script>
